<?php 
/**
 * 购物车控制器
 * @author 杨帆
 */
class ShopCarController extends CommonController{
    /**
     * 购物车显示
     */
    public function index(){
       $carGoods = Cart::getGoods();
       //将规格由数组变为字符串;
       foreach ($carGoods as $k => $v) {
           	$carGoods[$k]['options'] = implode(',',$v['options']);
       }
//     p($carGoods);
       $this->assign('carGoods',$carGoods);
       //商品总价格
       $totalPrice = Cart::getTotalPrice();
       $this->assign('totalPrice',$totalPrice);
       //p($totalPrice);
       //商品总件数
       $totalNum = Cart::getTotalNums();
       $this->assign('totalNum',$totalNum);
       $this->display(); 
    }
    /**
     * 添加购物车信息
     */
    public function add(){
        //商品id
        $gid = Q('post.gid',0,'intval');
        //商品规格属性id
        $tid =Q('post.id');
        $tid = (substr($tid,0,strlen($tid)-1));
        //商品主表数据
        $name = M('goods')->where("gid={$gid}")->find();
        //建立一个空数组
        $temp = array();
        //商品单价
        $price = $name['shop_price'];
        //商品属性表数据
        $attr = M()->join('__goods_attr__ ga join __attribute__ at ON ga.attrid=at.attrid')->where("ga.gaid in({$tid})")->all();
        foreach ($attr as $v) {
            $temp[$v['title']] = $v['ganame'];
            $price += $v['add_price'];	
        }
        $data = array( 
            'id' => $gid, // 商品 ID ok
            'name'=> $name['gname'],// 商品名称 ok
            'num' => Q('post.fqty',0,'intval'), // 商品数量 ok
            'price' => intval($price), // 商品价格 
            'options' => $temp,
        );
        Cart::add($data);
    }
    /**
     * 购物车商品删除
     */
    public function del(){
        $sid = ($_GET['sid']);
        Cart::del($sid);
        $this->success('商品删除成功','index');
    }
    
    /**
     * 异步处理加减改变商品数量和商品总价
     */
    public function ajaxGetNum(){
        if(!IS_AJAX) $this->error('非法请求');
        
        $data = array(
            'sid'   =>Q('post.sid'),
            'num'  =>Q('post.num',0,'intval'),
        );
        //更新商品
        Cart::update($data);
        //总金额
        $total['num'] = Cart::getTotalPrice();
        //总件数
        $total['nums']  =Cart::getTotalNums();
//      p(Cart::getAllData());
//      p(Q('post.sid'));
        foreach(current(Cart::getAllData()) as $k=>$v){
            if($k==Q('post.sid')){
                $total['goods']=$v;
            }
        }
//      p($total);
        $this->ajax($total);
    }
    
    
    
    
    
    
    
 }
 
 
 
 
 
 
 
 
 
 
 



 ?>